import {
  readCSV,
  splitPerson,
  getDateByStr,
  getTimeByStr,
  cloneObj,
} from "./utils.js";
const dayjs = require("dayjs");
var weekOfYear = require("dayjs/plugin/weekOfYear");
dayjs.extend(weekOfYear);
export default {
  data() {
    return {
      headerKey: "#早起读书现学现卖#",
      bottomKey: "读书作业请不要在知识星球以及其他互联网渠道发表",
      bottomKey2: "行动攻略-S中国思想史专题读书",
      startKey: "持续行动第",
      endKey: "天",
      baseDateObj: {},
      maxWeek: 0,
      maxYearWeek: 0,
    };
  },
  computed: {
    nicknameObj() {
      return this.$store.getters.getNickNameObj();
    },
    qqObj() {
      return this.$store.getters.getQQObj();
    },
    nickNameObj() {
      return this.$store.getters.getNickNameObj();
    },
  },
  methods: {
    // 从csv文件读取
    async readCSV() {
      let text = await this.$global.getFileText("base");
      if (!text) {
        this.$global.log("请选择csv文件");
        return;
      }
      let rows = readCSV(text);
      let titleIndex = -1;
      for (let i = 0, n = rows.length; i < n; i++) {
        let row = rows[i];
        let columns = row.split(",");
        if (columns[0] === "序号") {
          titleIndex = i;
          break;
        }
      }
      if (titleIndex === -1) {
        this.$global.log("请选择csv文件");
        return;
      }
      let titleText = rows[titleIndex];
      let tits = titleText.split(",");
      let nicknameIndex = tits.indexOf("群昵称");
      let indexObjs = {};
      let curW = 1;
      for (let i = nicknameIndex + 1, n = tits.length; i < n; i++) {
        let tit = tits[i].trim();
        let wkey = "W" + curW;
        if (tit.indexOf("规划") > -1) {
          let index = tit.substr(0, tit.indexOf("规划")).replace("W", "");
          index = parseInt(index);
          curW = index;
          wkey = "W" + curW;
        }
        if (!indexObjs[wkey]) {
          indexObjs[wkey] = {
            planIndex: -1,
            daysIndexs: [],
            daysNames: [],
          };
        }
        if (tit === wkey + "规划") {
          indexObjs[wkey].planIndex = i;
        } else if (!tit || tit.includes("规划") || tit.includes("存量")) {
          continue;
        } else {
          indexObjs[wkey].daysIndexs.push(i);
          indexObjs[wkey].daysNames.push(tit);
        }
      }
      let allWeek = curW;
      let list = [];
      for (let i = titleIndex + 1, n = rows.length; i < n; i++) {
        let row = rows[i].split(",");
        let nickname = row[nicknameIndex];
        if (!nickname) {
          continue;
        }
        let weeks = [];
        for (let j = 1; j <= allWeek; j++) {
          let wkey = "W" + j;
          let planIndex = indexObjs[wkey].planIndex;
          let daysIndexs = indexObjs[wkey].daysIndexs;
          let normalDates = indexObjs[wkey].daysNames;
          let plan = (planIndex > -1 && row[planIndex]) || "";
          let days = daysIndexs.map((index) => {
            return row[index];
          });
          weeks.push({
            w: wkey,
            plan: plan,
            days: days,
            normalDates: normalDates,
          });
        }
        let qq = this.nicknameObj[nickname].qq;
        list.push({
          qq,
          nickname,
          weeks,
        });
      }
      this.timeList = list;
    },
    // 从QQ记录读取
    async readQQRecords() {
      let text = await this.$global.getFileText("base");
      if (!text) {
        this.$global.log("请选择大群文件");
        return;
      }
      let members = this.members;
      if (members.length === 0) {
        this.$global.log("请先导入成员");
        return;
      }
      this.baseDateObj = {};
      let maxWeek = 0;
      let maxYearWeek = 0;
      let qqObj = this.qqObj;
      let nickNameObj = this.nickNameObj;

      let headerKey = this.headerKey;
      let bottomKey = this.bottomKey;
      let bottomKey2 = this.bottomKey2;
      let searchList = [];
      let noEndObj = {};

      let allList = splitPerson(text);
      for (let i = 0, n = allList.length; i < n; i++) {
        let item = allList[i];
        let content = allList[i].content;
        if (!content) {
          continue;
        }
        if (item.qq) {
          if (!qqObj[item.qq]) {
            continue;
          }
          if (item.nickname !== qqObj[item.qq].nickname) {
            item.nickname = qqObj[item.qq].nickname;
          }
        } else {
          if (!nickNameObj[item.nickname]) {
            continue;
          }
          item.qq = nickNameObj[item.nickname].qq;
        }
        let day = 1;
        if (content.includes(this.startKey)) {
          let str = content.substr(
            content.indexOf(this.startKey) + this.startKey.length
          );
          str = str.substr(0, str.indexOf(this.endKey));
          day = parseInt(str.trim());
          item.day = day;
        }
        let searchKey = this.startKey + day + this.endKey;

        let isBottom =
          content.includes(bottomKey) || content.includes(bottomKey2);
        if (content.includes(headerKey) && noEndObj[item.nickname]) {
          let newItem = noEndObj[item.nickname];
          searchList.push(newItem);
          delete noEndObj[item.nickname];
        }
        if (content.includes(searchKey)) {
          if (!isBottom) {
            if (noEndObj[item.nickname]) {
              searchList.push(noEndObj[item.nickname]);
            }
            noEndObj[item.nickname] = item;
            continue;
          }
          if (!content.includes(headerKey)) {
            item.headerError = true;
          }
          searchList.push(item);
        } else {
          if (isBottom && noEndObj[item.nickname]) {
            let newItem = noEndObj[item.nickname];
            newItem.content += content;
            searchList.push(newItem);
            delete noEndObj[item.nickname];
          }
        }
      }
      for (let key in noEndObj) {
        searchList.push(noEndObj[key]);
      }
      let analyResult = [];
      for (let i = 0, n = searchList.length; i < n; i++) {
        let item = searchList[i];
        let resultItem = this.getResultItem(item);
        analyResult.push(resultItem);
      }
      analyResult = analyResult.sort((a, b) => (a.time > b.time ? 1 : -1));
      let obj = {};
      for (let i = analyResult.length - 1; i >= 0; i--) {
        let item = analyResult[i];
        let checkKey = item.qq + item.day;
        if (obj[checkKey]) {
          analyResult.splice(i, 1);
          obj[checkKey].firstSubmitTime = item.time;
          obj[checkKey].isDelay = item.isDelay;
          obj[checkKey].isLate = item.isLate;
        } else {
          obj[checkKey] = item;
        }
      }
      let qqResultObj = {};
      let weekDays = {};
      for (let i = 0, n = analyResult.length; i < n; i++) {
        let item = analyResult[i];
        if (!qqResultObj[item.qq]) {
          qqResultObj[item.qq] = [];
        }
        qqResultObj[item.qq].push(item);
        let obj = this.baseDateObj[item.day];
        if (obj && obj.week) {
          continue;
        }
        let date = dayjs(item.date);
        let baseWeek = date.week();
        if (baseWeek > maxYearWeek) {
          maxYearWeek = baseWeek;
          maxWeek += 1;
        }
        this.baseDateObj[item.day].yearWeek = maxYearWeek;
        this.baseDateObj[item.day].week = maxWeek;
        let wkey = "W" + maxWeek;
        if (!weekDays[wkey]) {
          weekDays[wkey] = [];
        }
        weekDays[wkey].push(item.day);
      }
      let timeList = [];
      let baseDateObj = this.baseDateObj;
      for (let member of members) {
        let list = qqResultObj[member.qq] || [];
        let obj = {};
        for (let i = 0, n = list.length; i < n; i++) {
          let item = list[i];
          obj[item.day] = item;
        }
        let weeks = [];
        for (let i = 0; i < maxWeek; i++) {
          let w = i + 1;
          let wkey = "W" + w;
          let plan = "";
          let days = [];
          let normalDates = [];
          for (let day of weekDays[wkey]) {
            let item = obj[day] || {};
            let showDay = item.firstSubmitTime || item.time || "-";
            if (item.isDelay) {
              showDay += "（补）";
            }
            days.push(showDay);
            let baseDate = baseDateObj[day].date;
            normalDates.push(baseDate);
          }
          weeks.push({
            w: wkey,
            plan: plan,
            days: days,
            normalDates: normalDates,
          });
        }
        timeList.push({
          qq: member.qq,
          nickname: member.nickname,
          weeks,
        });
      }
      this.timeList = timeList;
    },
    getResultItem(item) {
      let nickNameObj = this.nickNameObj;
      let lateTime = "23:30:00";
      let isDelay = false;
      let isLate = false;
      if (item.time) {
        let addDate = getDateByStr(item.time);
        let time = getTimeByStr(item.time);
        let obj = this.baseDateObj[item.day];
        let baseDate = "";
        if (!obj) {
          this.baseDateObj[item.day] = {
            date: addDate,
          };
          baseDate = addDate;
        } else {
          baseDate = obj.date;
        }
        if (addDate > baseDate) {
          isDelay = true;
        }
        if (time > lateTime) {
          isLate = true;
        }
      }
      return {
        qq: item.qq || nickNameObj[item.nickname].qq,
        nickname: item.nickname,
        time: item.time,
        date: item.date,
        day: item.day,
        count: item.content.length,
        title: item.title,
        content: item.content,
        isDelay: isDelay,
        isLate: isLate,
        isLeave: nickNameObj[item.nickname].isLeave,
        headerError: item.headerError,
        no: nickNameObj[item.nickname].no,
      };
    },
  },
};
